package com.xiaoxx.common.swagger;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Collections;
import java.util.List;

/**
 * @author :HX
 * @date : 2023/7/19
 */
@Configuration
@EnableOpenApi
public class SwaggerConfig {
    @Bean
    public Docket createRestApi(Environment environment) {
        Profiles profiles = Profiles.of("dev");
        boolean b = environment.acceptsProfiles(profiles);
        return new Docket(DocumentationType.OAS_30)
                .enable(b)
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo())
                // 全局参数 -> 默认token参数
                .globalRequestParameters(getGlobalParameters());
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("XIAOXX", "www.baidu.com", "1624242879@qq.com");
        return new ApiInfoBuilder()
                .title("swaggerAPI")
                .contact(contact)
                .description("接口文档")
                .license("Apache License Version 2.0")
                .version("v1.0")
                .build();
    }

    /**
     * @author HX
     * @create 2022/2/28 11:10
     * @desc
     **/
    private List<RequestParameter> getGlobalParameters() {
        return Collections.singletonList(
                new RequestParameterBuilder()
                        .name("Authorization")
                        .description("请求头参数")
                        .in(ParameterType.HEADER)
                        .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                        .description("Global parameter description")
                        .required(false)
                        .build()
        );
    }
}


